using AutoMapper;
using Common.Communal;
using ERP.Domain.Products;
using MediatR;
using Product.API.ISerivces.Bom;
using Product.API.Write.Applications.Commands.Bom;
using System.Transactions;

namespace Product.API.Write.Applications.CommandHandlers.Bom
{
    /// <summary>
    /// Bom修改命令处理
    /// </summary>
    public class UpdateBomCommandHandler : IRequestHandler<UpdateBomCommand, ApiResult<int>>
    {
        /// <summary>
        /// Bom服务
        /// </summary>
        private readonly IBomSerivces bomSerivces;
        private readonly IMapper mapper;

        /// <summary>
        /// 构造方法
        /// </summary>
        /// <param name="bomSerivces">Bom服务</param>
        /// <param name="mapper">映射</param>
        public UpdateBomCommandHandler(IBomSerivces bomSerivces, IMapper mapper)
        {
            this.bomSerivces = bomSerivces;
            this.mapper = mapper;
        }

        /// <summary>
        /// 处理
        /// </summary>
        /// <param name="request">请求</param>
        /// <param name="cancellationToken">取消</param>
        /// <returns>返回任务</returns>
        public async Task<ApiResult<int>> Handle(UpdateBomCommand request, CancellationToken cancellationToken)
        {
            ApiResult<int> result = new ApiResult<int>();
            result.Code = EnumCode.Ok;
            result.Message = EnumCode.Ok.ToString();

            var entity = mapper.Map<BomInfo>(request);
            try
            {
                using (var scope = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled))
                {
                    await bomSerivces.UpdateBom(entity);

                    if (request.batchUpdateMaterialStructuer != null && request.batchUpdateMaterialStructuer.Count > 0)
                    {
                        await bomSerivces.BatchUpdateMaterial(request.batchUpdateMaterialStructuer, request.BomNumber);
                    }

                    if (request.batchUpdateProductMaterial != null && request.batchUpdateProductMaterial.Count > 0)
                    {
                        await bomSerivces.BatchUpdateProductMaterial(request.batchUpdateProductMaterial, request.ProductNumber ?? Guid.Empty, request.SerialNumber);
                    }

                    scope.Complete();
                }

                result.Data = 1;
            }
            catch (Exception)
            {
                result.Code = EnumCode.Fail;
                result.Message = EnumCode.Fail.ToString();
                result.Data = 1;
            }

            return await Task.FromResult(result);
        }
    }
}


